<template>
  <div class="app-container">
    <mainTilte title="基本信息" />
    <el-form ref="addForm" :inline="true" :rules="roleCodeRule" :model="addForm" label-width="110px">
      <el-row>
        <el-col :span="9">
          <el-form-item label="采购申请单编码" prop="code">
            <el-input v-model.trim="addForm.code" placeholder="采购申请单编码" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="15">
          <el-form-item label="备注说明" prop="notes">
            <el-input v-model="addForm.notes" type="textarea" autosize placeholder="备注说明" style="width: 300px" maxlength="500" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <mainTilte title="商品信息" />
      </el-row>
      <el-row style="margin-bottom: 10px">
        <el-button type="primary" icon="el-icon-circle-plus" @click="addProcuctClick">添加商品</el-button>
      </el-row>
      <el-table :data="addForm.products" stripe fit border>
        <el-table-column type="selection" width="55" />
        <el-table-column fixed="left" label="操作" width="100" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="small" style="color: #ff4444" @click="deleteProductClick(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
        <el-table-column label="币别" width="150" align="center">
          <template slot-scope="scope">
            <app-text :text="scope.row.currencyType" />
          </template>
        </el-table-column>
        <el-table-column label="缩略图" width="150" align="center">
          <template slot-scope="scope">
            <thund :img="scope.row.goods_pic" />
          </template>
        </el-table-column>
        <el-table-column prop="goods_code" label="系统sku" width="180" align="center" />
        <el-table-column label="采购数量" prop="number" width="200" align="center">
          <template slot-scope="scope">
            <el-form-item class="no-label mt22" :prop="'products.' + scope.$index + '.number'" :rules="[{required: true,message: '采购数量不能为空',trigger: 'blur',}]">
              <el-input-number v-model="scope.row.number" :precision="0" placeholder="请输入采购数量" :min="1" :max="9999999999" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="delivery_date" label="需求时间" min-width="260" align="center">
          <template slot-scope="scope">
            <el-form-item class="no-label mt22" :prop="'products.' + scope.$index + '.delivery_date'" :rules="[{required: true,message: '需求时间不能为空',trigger: 'blur',}]">
              <el-date-picker v-model="scope.row.delivery_date" type="month" placeholder="选择需求时间" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="备注" width="220" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.notes" type="textarea" autosize maxlength="50" />
          </template>
        </el-table-column>
        <el-table-column prop="goods_name" label="中文名称" width="180" align="center" />
        <el-table-column prop="goods_name_en" label="英文名称" width="180" align="center" />
        <el-table-column prop="buyer" label="采购员" width="180" align="center" />
        <el-table-column prop="container_rate" label="箱率" width="180" align="center" />
      </el-table>
      <el-row>
        <mainTilte title="配件信息" />
      </el-row>
      <el-row style="margin-bottom: 10px">
        <el-button type="primary" icon="el-icon-circle-plus" @click="addPartClick">添加配件</el-button>
      </el-row>
      <el-table :data="addForm.parts" stripe fit border>
        <el-table-column type="selection" width="55" />
        <el-table-column fixed="left" label="操作" width="100" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="small" style="color: #ff4444" @click="deletePartClick(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
        <el-table-column label="缩略图" width="150" align="center">
          <template slot-scope="scope">
            <thund :img="scope.row.goods_pic" />
          </template>
        </el-table-column>
        <el-table-column prop="goods_code" label="配件编码" width="180" align="center" />
        <el-table-column label="采购数量" prop="number" min-width="180" align="center">
          <template slot-scope="scope">
            <el-form-item class="no-label mt22" :prop="'parts.' + scope.$index + '.number'" :rules="[{required: true,message: '采购数量不能为空',trigger: 'blur'}]">
              <el-input-number v-model="scope.row.number" :precision="0" placeholder="请输入采购数量" :min="1" :max="9999999999" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column prop="delivery_date" label="需求时间" min-width="260" align="center">
          <template slot-scope="scope">
            <el-form-item class="no-label mt22" :prop="'parts.' + scope.$index + '.delivery_date'" :rules="[{required: true,message: '需求时间不能为空',trigger: 'blur',},]">
              <el-date-picker v-model="scope.row.delivery_date" type="month" placeholder="选择需求时间" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="备注" width="220" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.notes" type="textarea" autosize maxlength="50" />
          </template>
        </el-table-column>
        <el-table-column prop="goods_name" label="配件名称" width="180" align="center" />
        <el-table-column prop="buyer" label="采购员" width="180" align="center" />
        <el-table-column prop="container_rate" label="箱率" width="180" align="center" />
      </el-table>
      <el-row style="text-align: center; margin-top: 20px">
        <span class="dialog-footer">
          <el-button :loading="canSaveLoading" type="primary" @click="saveProductData">保存</el-button>
          <el-button @click="cancelProductClick">取消</el-button>
        </span>
      </el-row>
    </el-form>
    <!-- 添加商品 -->
    <el-dialog v-if="dialogAddProductVisible" v-loading.lock="loading" v-loading="loading" title="" :visible.sync="dialogAddProductVisible" :close-on-click-modal="false" width="90%" class="dialogText header-none" :element-loading-text="loadingText" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)" center>
      <addProduct type="purchase" :is-purchase="true" @checkChildIds="checkChildIds" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogAddProductVisible = false">取消选择</el-button>
        <el-button type="primary" @click="saveData()">确认选择</el-button>
      </span>
    </el-dialog>
    <!-- 添加配件 -->
    <el-dialog v-if="dialogAddPartVisible" v-loading.lock="loading" v-loading="loading" title="" :visible.sync="dialogAddPartVisible" :close-on-click-modal="false" width="90%" class="dialogText header-none" :element-loading-text="loadingText" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)" center>
      <addPart @checkedPartIds="checkedPartIds" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogAddPartVisible = false">取消选择</el-button>
        <el-button type="primary" @click="savePartClick">确认选择</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import addProduct from '../components/addProduct.vue'
import addPart from '../components/addPart.vue'
import appText from '@/components/appText/index.vue'
export default {
  name: 'PurchaseRequisitionAdd',
  components: { addProduct, addPart, appText },
  data() {
    return {
      canSaveLoading: false,
      value: '',
      loadingText: '',
      loading: false,
      addForm: { code: '', notes: '', products: [], parts: [], currency: '' },
      dialogAddProductVisible: false,
      checkChildList: [],
      code: '',
      notes: '',
      isableSave: false,
      isEdit: false,
      dialogAddPartVisible: false, // 添加配件弹框
      checkedPartList: [],
      roleCodeRule: {}
    }
  },
  mounted() {
    if (this.$route.query && this.$route.query.id) {
      this.isEdit = true
      this.getDatailData(this.$route.query.id)
    }
  },
  methods: {
    getDatailData(id) {
      this.$http
        .get(`/purchase-order/${id}`)
        .then((res) => {
          if (res.code === 10000) {
            this.addForm = res.data
            if (res.data.products) {
              this.addForm.products = res.data.products.map((arr) => {
                arr.purchase_id = this.addForm.purchase_id
                arr['currencyType'] = res.data.currency.toUpperCase()
                return arr
              })
            }
            if (res.data.parts) {
              this.addForm.parts = res.data.parts.map((arr) => {
                arr.purchase_id = this.addForm.purchase_id
                return arr
              })
            }
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    deleteClick(row) {
      this.addForm.products = this.addForm.products.filter((item) => {
        return item.id !== row.id
      })
    },
    deleteProductClick(index) {
      this.addForm.products.splice(index, 1)
    },
    deletePartClick(index) {
      this.addForm.parts.splice(index, 1)
    },
    addProcuctClick() {
      this.dialogAddProductVisible = true
    },
    isRepeat(array, key) {
      const midlle = array.every((item) => item['purchase_id'] === key)
      return midlle
    },
    saveData() {
      const dataLength = this.checkChildList.length
      if (dataLength === 0) {
        this.$message.error('请至少选择一条数据')
        return false
      }
      const isableSave = this.isRepeat(
        this.checkChildList,
        this.checkChildList[0]['purchase_id'] || this.addForm.purchase_id
      )
      let isProduct = true
      if (this.addForm.products.length > 0) {
        isProduct = this.isRepeat(
          this.checkChildList,
          this.addForm.products[0]['purchase_id'] || this.addForm.purchase_id
        )
      }
      console.log(`{ isableSave: ${isableSave}, isProduct: ${isProduct} }`)
      if (!isableSave || !isProduct) {
        this.$message.error('请选择同一个采购员的商品')
        return false
      }
      this.checkChildList.forEach((ele) => {
        // 去重
        // const index = this.addForm.products.findIndex((e) => e.goods_id === ele.id)
        // if (index > -1) {
        //   this.addForm.products.splice(index, 1)
        // }
        const productObj = {
          type: 1, // 商品
          goods_id: ele.id,
          supply_id: ele.supplier_id,
          goods_pic: ele.image_url,
          picture: ele.image_url,
          goods_code: ele.code,
          goods_name: ele.name_ch,
          goods_name_en: ele.name_en,
          category_name: ele.category_name,
          price: ele.currencyType === 'USD' ? ele.purchase_price_usd : ele.purchase_price_rmb,
          buyer: ele.purchase_name,
          purchase_id: ele.purchase_id,
          container_rate: ele.box_rate,
          currencyType: ele.currencyType,
          upc: ele.bar_code_upc,
          number: '',
          delivery_date: '',
          notes: ''
        }
        this.addForm.products.push(productObj)
        this.addForm.currency = ele.currencyType.toLowerCase()
        this.addForm.purchase_id = ele.purchase_id
        this.addForm.purchase_name = ele.purchase_name
        this.dialogAddProductVisible = false
      })
      console.log('products--------------------')
      console.log(this.addForm.products)
    },
    checkChildIds(data) {
      this.checkChildList = data
    },
    cancelProductClick() {
      this.$router.push('/supplyChain/purchaseRequisition')
    },
    // 配件
    addPartClick() {
      this.dialogAddPartVisible = true
    },
    checkedPartIds(data) {
      this.checkedPartList = data
    },
    savePartClick() {
      const dataLength = this.checkedPartList.length
      if (dataLength === 0) {
        this.$message.error('请至少选择一条数据')
        return false
      }
      const isableSave = this.isRepeat(
        this.checkedPartList,
        this.checkedPartList[0]['purchase_id']
      )
      let isProduct = true
      if (this.addForm.parts.length > 0) {
        isProduct = this.isRepeat(
          this.checkedPartList,
          this.addForm.parts[0]['purchase_id']
        )
      }
      console.log(`{ isableSave: ${isableSave}, isProduct: ${isProduct} }`)
      if (!isableSave || !isProduct) {
        this.$message.error('请选择同一个采购员的配件')
        return false
      }
      this.checkedPartList.forEach((ele) => {
        // 去重
        // const index = this.addForm.parts.findIndex((e) => e.goods_id === ele.id)
        // if (index > -1) {
        //   this.addForm.parts.splice(index, 1)
        // }
        const productObj = {
          type: 2, // 配件
          goods_id: ele.id,
          supply_id: ele.supplier_id,
          goods_pic: ele.image_url,
          picture: ele.image_url,
          goods_code: ele.code,
          goods_name: ele.name_ch,
          goods_name_en: ele.name_en || '',
          category_name: ele.category_name,
          price: 0,
          buyer: ele.purchase_name,
          purchase_id: ele.purchase_id,
          container_rate: ele.box_rate,
          number: '',
          delivery_date: '',
          notes: ''
        }
        this.addForm.parts.push(productObj)
        this.addForm.purchase_id = ele.purchase_id
        this.addForm.purchase_name = ele.purchase_name
        this.dialogAddPartVisible = false
      })
    },
    saveProductData() {
      const form = this.$refs['addForm']
      const length = this.addForm.products.concat(this.addForm.parts).length
      if (length <= 0) {
        return this.$message.error('请选择至少一个商品或配件')
      }
      // 判断 所选商品和配件是否是同一个采购员
      const { products, parts } = this.addForm
      const goods = products.concat(parts)
      console.log('=======goods=====', goods)
      const every = goods.every(e => e.purchase_id === goods[0].purchase_id)
      if (!every) {
        return this.$message.error('所选商品和配件必须是同一个采购员')
      }
      const everyCurrecyType = products.every(e => e.currencyType === products[0].currencyType)
      if (!everyCurrecyType) {
        return this.$message.error('所选商品必须是同一个币别的')
      }
      form.validate((valid) => {
        if (valid) {
          this.canSaveLoading = true
          const param = {
            notes: this.addForm.notes,
            products: this.addForm.products,
            parts: this.addForm.parts,
            currency: this.addForm.currency,
            purchase_id: this.addForm.purchase_id,
            purchase_name: this.addForm.purchase_name
          }
          if (this.isEdit) {
            this.$http
              .put(`/purchase-order/${this.addForm.id}`, param)
              .then((res) => {
                if (res.code === 10000) {
                  this.$message.success('修改成功')
                  this.$router.push('/supplyChain/purchaseRequisition')
                }
                this.canSaveLoading = false
              })
              .catch((err) => {
                console.log(err)
                this.canSaveLoading = false
              })
          } else {
            this.$http
              .post(`/purchase-order`, param)
              .then((res) => {
                if (res.code === 10000) {
                  this.$message.success('新增成功')
                  this.$router.push('/supplyChain/purchaseRequisition')
                }
                this.canSaveLoading = false
              })
              .catch((err) => {
                this.canSaveLoading = false
                console.log(err)
              })
          }
        }
      })
    }
  }
}
</script>

<style>
</style>
